<template>
  <div>
    <!-- 团体竞技成员选择 -->
    <van-popup v-model="dialogVisible" closeable position="bottom" :duration="0.16" :style="{ height: '100%' }">
      <van-loading v-if="dialogLoading" class="loadingStyle" />
      <div class="dialog_wrap">
        <div class="dialog_title gl_mb_15">成员选择</div>
        <!-- 分组模块 -->
        <div class="member_item gl_mb_10">
          <div class="member_title gl_clear">
            <span class="gl_fl">已选成员</span>
            <van-icon class="icon_mt gl_fr" name="add-o" size="24" color="#0d97ef" @click="showActionSheet" />
          </div>
          <div class="member_content">
            <div class="gl_mb_15">
              <span class="gl_mr_5 gl_middle">{{ mainMember.name }}</span>
              <span v-if="mainMember.genderCode === 'M'">(男)</span>
              <span v-if="mainMember.genderCode === 'W'">(女)</span>
            </div>
            <div v-for="(jtem, jndex) in rightList" :key="jndex" class="gl_mb_15 gl_clear">
              <span class="gl_mr_5 gl_middle gl_fl">{{ jtem.name }}</span>
              <van-icon
                class="gl_middle gl_mr_5 gl_fr"
                name="cross"
                size="16"
                color="#c8c9cc"
                @click="removeMember(jtem, jndex)"
              />
            </div>
          </div>
        </div>

        <!-- 控制按钮 -->
        <van-row :gutter="10" class="bottom_btn_position">
          <van-col v-if="teamEntry.teamEntryId" span="12" align="center">
            <van-button type="danger" block @click="deleteGroup">删除整组</van-button>
          </van-col>
          <van-col :span="teamEntry.teamEntryId ? 12 : 24" align="center">
            <van-button type="info" block @click="submit()">确定</van-button>
          </van-col>
        </van-row>
      </div>
    </van-popup>
    <van-action-sheet
      v-model="actionVisible"
      :actions="leftList"
      :description="leftList.length ? '' : '暂无可选人员'"
      cancel-text="取消"
      @select="changeMemberToRight"
    />
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: '成员选择'
    },
    ignoreCheck: {
      type: Boolean,
      default: false
    },
    requireMember: {
      type: Object,
      required: true,
      default() {
        return {};
      }
    },
    minSelectMemberNum: {
      type: Number,
      default: 1
    },
    maxSelectMemberNum: {
      type: Number,
      default: 0
    },
    optionMember: {
      type: Array,
      required: true,
      default() {
        return [];
      }
    },
    selectMember: {
      type: Array,
      default() {
        return [];
      }
    },
    teamEntry: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data () {
    return {
      dialogVisible: false,
      actionVisible: false,
      dialogLoading: false,
      mainMember: {},
      leftList: [],
      rightList: [],
      computeSelectMemberNum: 0
    };
  },
  computed: {
    computeRightListLen () {
      if (this.requireMember.id || this.requireMember.registerId) {
        return this.rightList.length + 1;
      } else {
        return this.rightList.length;
      }
    }
  },
  watch: {
    dialogVisible (val) {
      if (!val) {
        // 窗口关闭
        this.mainMember = {};
        this.leftList = [];
        this.rightList = [];
      }
    }
  },
  methods: {
    // 打开
    open () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.initData();
      });
    },
    close () {
      this.dialogVisible = false;
      this.actionVisible = false;
      this.dialogLoading = false;
    },
    showActionSheet () {
      this.actionVisible = true;
    },
    hideLoading () {
      this.dialogLoading = false;
    },
    // 初始化数据，拷贝数据
    initData () {
      this.mainMember = JSON.parse(JSON.stringify(this.requireMember));
      const _optionMember = JSON.parse(JSON.stringify(this.optionMember)) || [];
      const _selectMember = JSON.parse(JSON.stringify(this.selectMember)) || [];

      this.leftList = _optionMember.filter(item => {
        const _iid = item.registerId || item.id;
        const _mid = this.mainMember.registerId || this.mainMember.id;
        // 借助本次循环，调整显示名称 start
        item._name = item.name;
        const _gender = this.matchMemberGender(item);
        item.name = item.name + _gender;
        // end
        return _iid !== _mid;
      });

      this.rightList = _selectMember.filter(item => {
        const _iid = item.registerId || item.id;
        const _mid = this.mainMember.registerId || this.mainMember.id;
        // 借助本次循环，调整显示名称 start
        item._name = item.name;
        const _gender = this.matchMemberGender(item);
        item.name = item.name + _gender;
        // end
        return _iid !== _mid;
      });
      this.matchMainMemberFromRightList();
    },
    matchMemberGender (data) {
      let _gender = '';
      if (data.genderCode && data.genderCode === 'M') {
        _gender = ' (男)';
      }
      if (data.genderCode && data.genderCode === 'W') {
        _gender = ' (女)';
      }
      return _gender;
    },
    // 从右侧列表中：匹配必选人员是否存在；匹配左侧列表是否存该人员
    matchMainMemberFromRightList () {
      for (let i = 0; i < this.rightList.length; i++) {
        const item = this.rightList[i];
        const _iid = item.registerId || item.id;
        const findMember = this.leftList.find(ktem => {
          const _kId = ktem.registerId || ktem.id;
          return _kId === _iid;
        });
        if (findMember) { // 在左侧列表找到该人员
          findMember['disabled'] = true;
        } else { // 在左侧列表没有找到该人员
          item['disabled'] = true;
          this.leftList.push(item);
        }
      }
    },
    deleteGroup () {
      this.$dialog.confirm({
        title: '提示',
        message: '您确定要删除整组成员吗？'
      })
        .then(
          () => {
            this.dialogLoading = true;
            this.$emit('onDeleteGroupMember');
          }
        );
    },
    // 确认按钮
    submit () {
      // 需要校验
      if (!this.ignoreCheck) {
        const _isPass = this.checkChooseListPass();
        // 校验未通过则直接返回
        if (!_isPass) return;
      }

      const _mainMember = JSON.parse(JSON.stringify(this.mainMember));
      const _rightList = JSON.parse(JSON.stringify(this.rightList));
      _rightList.unshift(_mainMember);
      this.dialogLoading = true;
      this.$emit('onTeamNoneCompetitionSubmit', _rightList);
    },
    // 校验选择的成员是否符合要求
    checkChooseListPass () {
      if (this.computeRightListLen < this.minSelectMemberNum) {
        this.$toast.fail(`最少应分配${this.minSelectMemberNum}名成员`);
        return false;
      }

      return true;
    },
    // 移除右侧成员
    removeMember (item, index) {
      item['disabled'] = false; // 原disabled
      this.rightList.splice(index, 1);
    },
    // 将所选成员移至右侧
    changeMemberToRight (currentMember) {
      if (this.computeRightListLen >= this.maxSelectMemberNum) {
        this.$toast.fail(`已达到最大成员数量，无法继续添加成员`);
        return;
      }

      currentMember['disabled'] = true;
      this.rightList.push(currentMember);
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog_wrap {
  padding: 0 15px 30px;
}
.dialog_title {
  height: 46px;
  font-size: 16px;
  line-height: 46px;
  color: #323233;
  font-weight: 500;
}
.member_item {
  padding: 10px 20px;
  padding-left: 20px;
  background: #ffffff;
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.10);
}

.member_title {
  line-height: 24px;
  font-size: 15px;
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
}
.member_content {
  // padding: 10px 0;
  font-size: 14px;
  line-height: 16px;
  color: #333;
  vertical-align: middle;
}

.icon_mt {
  margin-top: 3px;
}

.loadingStyle {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 11;
  background-color: rgba(255, 255, 255, 0.7);
  text-align: center;
}
</style>

